package com.fhzn.auth.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fhzn.auth.constant.Constants;
import com.fhzn.auth.entity.App;
import com.fhzn.auth.enums.WebResponseEnum;
import com.fhzn.auth.mapper.AppMapper;
import com.fhzn.auth.service.AppService;
import com.fhzn.auth.service.OperatorLogService;
import com.fhzn.auth.service.RoleService;
import com.fhzn.auth.web.converter.AppConverter;
import com.fhzn.auth.web.request.AppOpRequest;
import com.fhzn.auth.web.request.AppQueryRequest;
import com.fhzn.auth.web.vo.AppVO;
import com.fhzn.commons.toolkit.exception.BuzException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 老顾
 * @apiNote
 * @since 2024/1/3
 */
@Service
@RequiredArgsConstructor
public class AppServiceImpl implements AppService {

    private final AppMapper appMapper;
    private final OperatorLogService operatorLogService;
    private final RoleService roleService;

    @Override
    public Page<App> appWithPage(AppQueryRequest request) {
        request.checkParams();
        request.rewriteParams();
        request.getOffset();
        return appMapper.getAppsWithPage(request);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppVO add(AppOpRequest request) {
        request.checkAdd();

        App app = request.genServiceParam();
        if (roleService.isSuperAdmin(request.getHandler())) {
            appMapper.insert(app);
        } else {
            throw new BuzException("无操作权限");
        }
        operatorLogService.operatorLog(request.getHandler(), Constants.APPLICATION_SECTION, Constants.APPLICATION_ADD_METHOD, request.getId(), null, app, Constants.AUTH_APP_CODE);
        return AppConverter.fromApp(app);
    }

    @Override
    public AppVO queryOne(AppQueryRequest request) {
        request.checkId();
        return AppConverter.fromApp(appMapper.selectById(request.getId()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String update(AppOpRequest request) {
        request.checkUpdate();
        App appBefore = appMapper.selectById(request.getId());
        if (roleService.isSuperAdmin(request.getHandler())) {
            appBefore.setModifier(request.getModifier());
            appMapper.updateById(request.genServiceParam());
        } else {
            throw new BuzException("无操作权限");
        }
        operatorLogService.operatorLog(request.getHandler(), Constants.APPLICATION_SECTION, Constants.APPLICATION_MESSAGE_UPDATE, request.getId(), appBefore, appMapper.selectById(request.getId()), Constants.AUTH_APP_CODE);
        return WebResponseEnum.SUCCESS.getMessage();
    }

    @Override
    public String export(AppOpRequest request) {
        return null;
    }
}
